<template>
    <el-dialog
    custom-class="ba-operate-dialog cu-dialog"
        :close-on-click-modal="false"
        :model-value="baTable.form.operate == 'wfrecord'"
        @close="onClosed();baTable.toggleForm"
        @open="onOpen"
        width="70%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                项目审批记录 - {{ baTable.form.items!.title }}
            </div>
        </template>
        <div class="container">
            <div class="warp-item">
                <div class="table-warp">
                    <el-tabs v-model="tabModel" @tab-change="onTabChange">
                        <el-tab-pane label="报销申请" name="reimbursement">
                            <el-table
                            :data="tableData.reimbursement.list"
                            style="width: 100%" 
                            :height="tableHeight"
                            :show-summary="true"
                            :summary-method="tableSummary"
                            @selection-change="handleSelectionChange"
                            :ref="(el) => setTableRef(el, 'reimbursement')">
                                <el-table-column type="selection" width="55" />
                                <el-table-column prop="no" label="单据号" width="155" />
                                <el-table-column prop="title" label="报销内容" />
                                <el-table-column prop="date" label="日期" width="180" />
                                <el-table-column prop="feeitem_title" label="费用项名称" width="180" >
                                    <template #default="{ row }">
                                        <div v-show="row.feeitem_title">{{ row.feeitem_title }}</div>
                                        <div :key="index" v-for="item,index in row.feeitems">【{{ item.feeitem_name }}】 {{ item.amount }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="amount" label="报销金额" width="100" />
                                <el-table-column prop="image" label="图片" width="100" >
                                    <template #default="{ row }">
                                        <el-image fit="cover" style="height: 50px;width: 50px;" class="images-item" :src="item" v-for="item, index in row.image" :key="index"></el-image>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="user_name" label="申请人" width="100" />
                                <el-table-column prop="audit_state" label="审核状态" width="100" >
                                    <template #default="{ row }">
                                        <el-tag :type="flowStateColor[row.audit_state]">{{ flowState[row.audit_state] }}</el-tag>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="预支申请" name="advance">
                            <el-table
                            :data="tableData.advance.list"
                            style="width: 100%"
                            :height="tableHeight"
                            :show-summary="true"
                            :summary-method="tableSummary"
                            @selection-change="handleSelectionChange"
                            :ref="(el) => setTableRef(el, 'advance')">
                                <el-table-column type="selection" width="55" />
                                <el-table-column prop="no" label="单据号" width="155" />
                                <el-table-column prop="date" label="日期" width="180" />
                                <el-table-column prop="feeitem_title" label="费用项名称" >
                                    <template #default="{ row }">
                                        <div v-show="row.feeitem_title">{{ row.feeitem_title }}</div>
                                        <div :key="index" v-for="item,index in row.feeitems">【{{ item.feeitem_name }}】 {{ item.amount }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="amount" label="预支金额" width="100" />
                                <el-table-column prop="user_name" label="申请人" width="100" />
                                <el-table-column prop="audit_state" label="审核状态" width="100" >
                                    <template #default="{ row }">
                                        <el-tag :type="flowStateColor[row.audit_state]">{{ flowState[row.audit_state] }}</el-tag>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="付款申请" name="payment" >
                            <el-table
                            :data="tableData.payment.list"
                            style="width: 100%"
                            :height="tableHeight"
                            :show-summary="true"
                            :summary-method="tableSummary"
                            @selection-change="handleSelectionChange"
                            :ref="(el) => setTableRef(el, 'payment')">
                                <el-table-column type="selection" width="55" />
                                <el-table-column prop="no" label="单据号" width="155" />
                                <el-table-column prop="date" label="日期" width="120" />
                                <el-table-column prop="supplier_company_name" label="供应商" />
                                <el-table-column prop="feeitem_title" label="费用项名称" width="180" >
                                    <template #default="{ row }">
                                        <div v-show="row.feeitem_title">{{ row.feeitem_title }}</div>
                                        <div :key="index" v-for="item,index in row.feeitems">【{{ item.feeitem_name }}】 {{ item.amount }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="pay_amount" label="付款金额" width="100" />
                                <el-table-column prop="pay_type" label="付款方式" width="100" />
                                <el-table-column prop="pay_time" label="付款时间" width="180" />
                                <el-table-column prop="account" label="付款账户" width="320" />
                                <el-table-column prop="user_name" label="申请人" width="100" />
                                <el-table-column prop="audit_state" label="审核状态" width="100" >
                                    <template #default="{ row }">
                                        <el-tag :type="flowStateColor[row.audit_state]">{{ flowState[row.audit_state] }}</el-tag>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </div>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="onClosed">{{ t('关闭') }}</el-button>
                <el-button @click="onExport" type="primary" :disabled="allowExport">{{ t('导出') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { inject, reactive, ref, onMounted, nextTick, h } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import { getProjectWfRecord } from '/@/api/backend/index'
import { fullUrl } from '/@/utils/common'
import { flowState, flowStateColor } from '/@/utils/enums'
import * as XLSX from 'xlsx/xlsx.mjs'
import { json } from 'stream/consumers'

const baTable = inject('baTable') as baTableClass
const tableHeight = ref()
const { t } = useI18n()
const tableRefs:any = {}
const allowExport = ref(true)

let lastTable: string = "reimbursement"
let selDatas: any[] = []

onMounted(() => {
    tableHeight.value = window.innerHeight * 0.6 - 127;    
})

let tableData: any = reactive({
    reimbursement: {
        header: ['单据号','报销内容','日期','费用项名称','报销金额','图片','申请人','审核状态'],
        field: ['no','title','date','feeitem_title','amount','image','user_name','audit_state'],
        title: '报销申请',
        list: []
    },
    advance: {
        header: ['单据号','日期','费用项名称','预支金额','申请人','审核状态'],
        field: ['no','date','feeitem_title','amount','user_name','audit_state'],
        title: '预支申请',
        list: []
    },
    payment: {
        header: ['单据号','日期','供应商','费用项名称','付款金额','付款方式','付款时间','付款账户','申请人','审核状态'],
        field: ['no','date','supplier_company_name','feeitem_title','pay_amount','pay_type','pay_time','account','user_name','audit_state'],
        title: '付款申请',
        list: []
    },
})
let tabModel = ref(lastTable)

const onOpen = () => {
    tableData.reimbursement.list = []
    tableData.advance.list = []
    tableData.payment.list = []
    getProjectWfRecord({project_id: baTable.form.items!.id}).then((res: any) => {
        const { advance, payment, reimbursement } = res.data
        reimbursement.forEach((item: any) => {
            item.feeitem_title = item.feeitem ? item.feeitem.title : ""
            try {
                item.feeitems = JSON.parse(item.feeitems)
            } catch (error) {
                item.feeitems = []
            }
            item.image = item.image.map((ele: string) => {
                return fullUrl(ele)
            })
            tableData.reimbursement.list.push(item)
        })
        advance.forEach((item: any) => {
            item.feeitem_title = item.feeitem ? item.feeitem.title : ""
            try {
                item.feeitems = JSON.parse(item.feeitems)
            } catch (error) {
                item.feeitems = []
            }
            tableData.advance.list.push(item)
        })
        payment.forEach((item: any) => {
            item.feeitem_title = item.feeitem ? item.feeitem.title : ""
            try {
                item.feeitems = JSON.parse(item.feeitems)
            } catch (error) {
                item.feeitems = []
            }
            item.supplier_company_name = item.supplier ? item.supplier.company_name : "";
            tableData.payment.list.push(item)
        })
    })
    
}

const onClosed = () => {
    baTable.toggleForm()
    tableData.value = []
}

const setTableRef = (el: any, tableName: string) => {
    if(el) {
        tableRefs[tableName] = el
    }
}

const onTabChange = (tabName: string) => {
    tableRefs[lastTable].clearSelection()
    lastTable = tabName
    selDatas = []
}

const handleSelectionChange = (val: any[]) => {
    selDatas = val
    allowExport.value = val.length == 0
    let sum = 0
    let dics = {
        reimbursement: {field: 'amount', tableIndex:2, colIndex: 5},
        advance: {field: 'amount', tableIndex:3, colIndex: 4},
        payment: {field: 'pay_amount', tableIndex:4, colIndex: 5},
    }
    selDatas.forEach((item: any) => {
        sum += Number(item[dics[lastTable]['field']])
    })
    const ele = document.querySelector(`#pane-${lastTable} .el-table__footer-wrapper > table  tfoot > tr > td .cell .cell${dics[lastTable]['colIndex']}`)
    setTimeout(() => {
        ele.innerHTML = sum
    }, 50)
}

const tableSummary = (param: any) => {
    const { columns, data } = param
    const sums: string[] = []
    sums[0] = '合计'
    sums[4] = h('div', {class: "cell4"}, "")
    sums[5] = h('div', {class: "cell5"}, "")
    sums[6] = h('div', {class: "cell6"}, "")
    return sums
}

const onExport = () => {
    const wb =  XLSX.utils.book_new()
    let sheetData = []
    let sum = 0
    let dics = {
        reimbursement: {field: 'amount', colIndex: 4},
        advance: {field: 'amount', colIndex: 3},
        payment: {field: 'pay_amount', colIndex: 4},
    }
    sheetData.push([...tableData[tabModel.value]['header']])
    selDatas.forEach((item) => {
        let rowData: any = []
        tableData[tabModel.value]['field'].forEach((field: string) => {
            if(field == 'image'){
                rowData.push(item[field].join('|'))
            } else if(field == 'audit_state') {
                rowData.push(flowState[item[field]])
            } else {
                rowData.push(item[field])
            }
            
        })
        sum += Number(item[dics[lastTable]['field']])
        sheetData.push(rowData)
    })
    let temp = []
    temp[0] = '合计'
    temp[dics[lastTable]['colIndex']] = sum
    sheetData.push(temp)
    const sheet = XLSX.utils.aoa_to_sheet(sheetData)
    XLSX.utils.book_append_sheet(wb, sheet);
    XLSX.writeFileXLSX(wb, baTable.form.items!.title+'-'+tableData[tabModel.value]['title']+'.xlsx', {
        bookType: 'xlsx',
        type: 'binary'
    })
}

</script>

<style scoped lang="scss">
    .ba-operate-dialog .el-dialog__body { padding-bottom: 0; }
    .info-content {
        border-right: 1px solid #ddd; height: calc(100vh - 175px);
        .info-content-item {
            display: flex; justify-content: space-between; padding: 5px 10px; align-items: center;
            .label { display: inline-block; white-space: nowrap; padding-right: 13px;}
            .value {
                .ml-2 { 
                    margin-bottom: 10px;
                    margin-right: 10px
                }
            }
            div.value {
                
            }
        }
    }
    .table-warp { }
    .title { font-size: 14px; font-weight: bold; padding: 8px 0; }
    .table-input-item { display: flex; justify-content: space-between; align-items: center; }
    .statics-warp {
        display: flex; 
        justify-content: flex-start;
        .statics-item {
            border: 1px solid #ddd; border-radius: 5px; box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
            width: 180px;
            .title { padding: 10px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between;}
            .content { padding: 10px; display: flex; justify-content: flex-end; }
        }
        .statics-item + .statics-item { 
            margin-left: 20px;
        }

    } 
</style>
